package com.my.reggie.util;
import com.my.reggie.config.WxPayConfig;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.notification.Notification;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationHandler;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationRequest;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

public class WechatPay2ValidatorForRequest {
    private final String wechatPaySerial; // 平台证书序列号
    private final String apiV3Key; // apiV3密钥
    private final String nonce; // 请求头Wechatpay-Nonce
    private final String timestamp;// 请求头Wechatpay-Timestamp
    private final String signature;// 请求头Wechatpay-Signature
    private final String body; // 请求体
    private final Verifier verifier; // 验签器

    public WechatPay2ValidatorForRequest(String wechatPaySerial, String apiV3Key, String nonce, String timestamp, String signature, String body, Verifier verifier) {
        this.wechatPaySerial = wechatPaySerial;
        this.apiV3Key = apiV3Key;
        this.nonce = nonce;
        this.timestamp = timestamp;
        this.signature = signature;
        this.body = body;
        this.verifier = verifier;
    }

    public Notification notificationHandler() throws Exception {
        // 构建request，传入必要参数
        NotificationRequest request = new NotificationRequest.Builder().withSerialNumber(wechatPaySerial)
                .withNonce(nonce)
                .withTimestamp(timestamp)
                .withSignature(signature)
                .withBody(body)
                .build();
        NotificationHandler handler = new NotificationHandler(verifier, apiV3Key.getBytes(StandardCharsets.UTF_8));
        // 验签和解析请求体
        return handler.parse(request);
    }
}
